const enterpriseVue = new Vue({
  el: "#app",
  data() {
    return {
      upLoadFilesList: new Array(new Array()),
      fileList: [],
      rules: {},
      form: [
        {
          Group_Rotation_SerialNumber: "",
          Group_Rotation_Name: "",
          Group_Rotation_URL: "",
          Picture_URL: "",
        },
      ],
      loading: false,
      dialogImageUrl: "",
      dialogVisible: false,
      index: 0,
    };
  },
  mounted() {
    this.getData();
  },
  methods: {
    dhandleRemove(file, index) {
      console.log(index);

      this.upLoadFilesList[index] = new Array();
      this.form[index].Picture_URL = "";
      this.$set(this, "upLoadFilesList", [...this.upLoadFilesList]);
    },
    dhandleBeforeUpload(file, index) {
      // console.log(file, fileList);
      // if (index == undefined) return;
      // 生成预览URL并添加到fileList中
      const reader = new FileReader();
      reader.onload = (e) => {
        const newFile = {
          name: file.name,
          url: e.target.result, // 预览URL
          uid: file.uid,
          // 可以添加其他属性，如上传状态等
        };

        if (!this.upLoadFilesList[index]) {
          this.upLoadFilesList[index] = [];
        }

        this.upLoadFilesList[index].push(newFile);
        console.log(this.upLoadFilesList, this.upLoadFilesList[index]);

        // console.log(newFile);
        const _this = this;
        // return;
        $.ajax({
          // headers: requestHeaders(), // 确保这个函数返回正确的头部信息
          url: "https://service.kdddy.cn/donghuiForRequest/store/photo",
          // url: "http://192.168.10.79:8087/store/photo",
          // url: "http://192.168.10.79:8087/store/photo",
          type: "POST", // 注意HTTP方法应该大写
          contentType: "application/json", // 设置请求体的媒体类型为application/json
          data: JSON.stringify(this.upLoadFilesList[index]), // 将数据序列化为JSON字符串
          success: function (Result) {
            console.log(Result);
            console.log(_this.upLoadFilesList[index]);

            let base64Image = _this.upLoadFilesList[index][0].url;
            let dataIndex = base64Image.indexOf("data:");
            let base64Index = base64Image.indexOf(";base64,");
            let substring = base64Image.substring(dataIndex + 5, base64Index);
            let ls_split = substring.split("/");
            _this.form[index].Picture_URL =
              _this.upLoadFilesList[index][0].uid + "." + ls_split[1];
            console.log(111, _this.form[index]);
          },
          //   complete: function (XMLHttpRequest) {
          //     requestPretreatment(XMLHttpRequest); // 确保这个函数在config/config.js中定义
          //   },
          dataType: "json", // 预期服务器返回的数据类型
        });
      };
      reader.readAsDataURL(file);
      // console.log(this.fmfileList);

      // 返回false以阻止自动上传
      return false;
    },
    showFileList: function (index) {
      // return function (url) {
      //   return url ? [url] : [];
      // };
      console.log("index", index, this.upLoadFilesList[index]);

      return this.upLoadFilesList[index];
    },
    handleBeforeUpload() {
      // 生成预览URL并添加到fileList中
      const reader = new FileReader();
      reader.onload = (e) => {
        //调用存储的接口放在onload中，存在异步操作
        const newFile = {
          name: file.name,
          url: e.target.result, // 预览URL
          uid: file.uid, //添加uid
          // 可以添加其他属性，如上传状态等
        };
        this.fileList.push(newFile);
        console.log(this.fileList);
        // return;
        $.ajax({
          // headers: requestHeaders(), // 确保这个函数返回正确的头部信息
          url: "https://service.kdddy.cn/donghuiForRequest/store/photo",
          // url: "http://192.168.10.79:8087/store/photo",
          type: "POST", // 注意HTTP方法应该大写
          contentType: "application/json", // 设置请求体的媒体类型为application/json
          data: JSON.stringify(this.fileList), // 将数据序列化为JSON字符串
          success: function (Result) {
            console.log(Result);
          },
          complete: function (XMLHttpRequest) {
            requestPretreatment(XMLHttpRequest); // 确保这个函数在config/config.js中定义
          },
          dataType: "json", // 预期服务器返回的数据类型
        });
      };
      reader.readAsDataURL(file);
      // 返回false以阻止自动上传

      return false;
    },
    add_form() {
      this.form.push({
        Group_Rotation_SerialNumber: "",
        Group_Rotation_Name: "",
        Group_Rotation_URL: "",
        Picture_URL: "",
      });
      this.upLoadFilesList.push(new Array());
      console.log(this.form);
      console.log(this.upLoadFilesList);
    },
    remove_form(index) {
      console.log(index);
      console.log(this.form);
      //   return;
      if (this.form.length == 1) {
        this.$message({
          message: "不能再删了!",
          type: "warning",
        });
      } else {
        console.log(index);
        console.log(this.upLoadFilesList);
        console.log(this.form);
        this.form.splice(index, 1);
      }
      return;
      if (this.form.filter((item) => item.Row_Status != "1").length > 0) {
        let i = this.form.filter((item) => item.Row_Status != "1").length - 1;
        let obj = this.form.filter((item) => item.Row_Status != "1")[i];
        if (!Object.keys(obj).some((item) => item.includes("_Original"))) {
          this.form.pop();
        } else {
          this.$confirm(
            "警告！此操作将删除一条已有的轮播图, 是否继续?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(() => {
              this.form.filter((item) => item.Row_Status != "1")[i].Row_Status =
                "1";
            })
            .catch(() => {
              this.$message({
                type: "warning",
                message: "已取消删除",
              });
            });
        }
      } else {
        this.$message({
          message: "不能在删除了",
          type: "warning",
        });
      }
    },
    remove_form1(index) {
      if (this.form.filter((item) => item.Row_Status != "1").length > 0) {
        let obj = this.form
          .filter((item) => item.Row_Status != "1")
          .filter((i, id) => index == id)[0];
        if (!Object.keys(obj).some((item) => item.includes("_Original"))) {
          this.form = this.form
            .filter((item) => item.Row_Status != "1")
            .filter((i, id) => index != id);
        } else {
          this.$confirm(
            "警告！此操作将删除一条已有的轮播图, 是否继续?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(() => {
              this.form
                .filter((item) => item.Row_Status != "1")
                .filter((i, id) => index == id)[0].Row_Status = "1";
            })
            .catch(() => {
              this.$message({
                type: "warning",
                message: "已取消删除",
              });
            });
        }
      } else {
        this.$message({
          message: "不能在删除了",
          type: "warning",
        });
      }
    },
    getData() {
      const _this = this;
      $.ajax({
        url: DomainName + "/GoodsFileInquiry_Original",
        type: "POST",
        data: {
          Data: "group_rotation_pic",
        },
        success: function (res) {
          _this.form = res;
          console.log(res);
        },
        error: function () {
          //   _this.$message.error("操作失败，请稍后再试");
        },
        //   complete: function (XMLHttpRequest) {
        //     if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
        //       window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
        //     }
        //   }
      });
    },
    submitForm(formName) {
      console.log();
      console.log(this.form);
      //   let lArray = new Array();
      //   lArray.push(this.form);
      let lJSONObject_group_rotation_pic = new Object();
      lJSONObject_group_rotation_pic.group_rotation_pic = this.form; //换表
      let lJSONObject_DataSet = new Object(); // Modify
      lJSONObject_DataSet.Add = lJSONObject_group_rotation_pic; //换表
      console.log(lJSONObject_DataSet);
      const _this = this;
      $.ajax({
        // headers: requestHeaders(),
        // url: `${BASE_URL2}/generalBusiness/generalPaginationQueryBySQLSerialNumber`,
        url: "https://service.kdddy.cn/donghui/clientOperation/generalSaveForClient",
        type: "POST",
        data: {
          Data: JSON.stringify(lJSONObject_DataSet),
        },
        success: function (Result) {
          console.log(Result);
          if (Result.Status === "success") {
            _this.$message({
              message: "提交成功",
              type: "success",
            });
            window.history.go(-1);
          } else {
            _this.$message.error("提交失败，请稍后再试");
          }
        },
        // complete: function (XMLHttpRequest) {
        //   requestPretreatment(XMLHttpRequest); //config/config.js 响应预检
        // },
        dataType: "json",
      });
      return;
      if (!this.loading) {
        const { add, modify } = _this.deal();
        let data = {};
        if (add == null) {
          data = {
            Data: JSON.stringify({ Modify: { group_rotation_pic: modify } }),
          };
        } else if (modify == null) {
          data = { Data: JSON.stringify({ Add: { group_rotation_pic: add } }) };
        } else {
          data = {
            Data: JSON.stringify({
              Modify: { group_rotation_pic: modify },
              Add: { group_rotation_pic: add },
            }),
          };
        }
        console.log(JSON.parse(data.Data));
        _this.loading = true;
        $.ajax({
          url: `${DomainName}/getEditAction?token=${$.cookie("token")}`,
          type: "POST",
          data,
          success: function (res) {
            if (res.Status === "success") {
              _this.$message.success("提交成功");
              window.history.go(-1);
            } else {
              _this.$message.error("提交失败，请稍后再试");
            }
          },
          error: function () {
            // _this.$message.error("操作失败，请稍后再试");
          },
          //   complete: function (XMLHttpRequest) {
          //     if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
          //       window.parent.document.location.href =
          //         "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          //     }
          //   },
        });
      }
    },
    upload(file) {
      const _this = this;
      new Compressor(file, {
        quality: 1,
        success(file) {
          const formData = new FormData();
          formData.append("file", file, file.name);
          let oFileReader = new FileReader();
          oFileReader.readAsDataURL(file);
          oFileReader.onload = function (e) {
            $.ajax({
              type: "POST",
              url: DomainName + "/FileList",
              data: {
                Data: e.target.result,
                DataLength: file.size,
                FileName: file.name,
              },
              complete: function (XMLHttpRequest) {
                _this.loading = false;
                if (
                  XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT"
                ) {
                  window.parent.document.location.href =
                    "../../../" +
                    XMLHttpRequest.getResponseHeader("CONTENTPATH");
                }
              },
              success: function (Result) {
                if (Result.Status == "success") {
                  _this.form.filter((item) => item.Row_Status != "1")[
                    _this.index
                  ].Picture_URL = Result.Picture_Url;
                  _this.$message.success("上传成功");
                } else {
                  _this.$message.error(Result.msg);
                }
              },
              error: function () {
                // _this.$message.error("操作失败，请稍后再试");
              },
              dataType: "json",
            });
          };
        },
        error(err) {
          console.log(err.message);
        },
      });
    },
    deal() {
      let add = [],
        modify = [];
      for (const i in this.form) {
        const obj = this.form[i];
        if (!Object.keys(obj).some((item) => item.includes("_Original"))) {
          add.push(obj);
        } else {
          modify.push(obj);
        }
      }
      if (add.length == 0) {
        return { add: null, modify };
      } else if (modify.length == 0) {
        return { add, modify: null };
      }
      return { add, modify };
    },
    handleIndex(index) {
      this.index = index;
    },
    //查看图片
    handlePictureCardPreview(file) {
      this.dialogVisible = true;
      this.dialogImageUrl = file;
    },
    //删除图片
    handleRemove(index) {
      this.form.filter((item) => item.Row_Status != "1")[index].Picture_URL =
        "";
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
});
